<?php
/**
 * @file tags.php
 * @author CaoQiCheng
 * @date 2017年2月8日 下午17:05:11
 * @brief 
 */
namespace haibao\jiepai\data;


class Fashionista extends \haibao\jiepai\data\BaseMysql{	
	public function __construct(){
		parent::__construct('\haibao\jiepai\model\data\fashionista\CmsFashionistas');
	}

	public function checkUserFollow($fashionstaId,$userId){
	    $isMark = 0;
        $sql = 'SELECT count(*) as MarkCount from cms_user_action WHERE Type=4 AND TypeID=%s and UserID=%s AND Flag = 0';
        $result = $this->query($sql, array($fashionstaId,$userId))->fetch_assoc();
        if(!empty($result) && !empty($result['MarkCount'])){
            $isMark = 1;
        }

        return $isMark;
    }

    public function getFollwFashionList($fashionstaIds,$userId){
	    $follwFashionstaIds = array();
        $str = implode(',',$fashionstaIds);
        $str = preg_replace('/(\d+)/','%s',$str);
        $sql = 'SELECT TypeID from cms_user_action WHERE Type=4 AND UserID=%s AND Flag = 0 and TypeID in ('.$str.')';
        $param = array_merge(array($userId),$fashionstaIds);
        $result = $this->query($sql,$param);
        while($result->fetch_assoc()){
            $follwFashionstaIds[] = $result->getData('TypeID');
        }

        return $follwFashionstaIds;
    }

    /**
     * 取消关注
     * @param $fashionstaIds
     * @param $userId
     * @param bool $isUpdateCache
     */
	public function delMarkFashionSta($fashionstaIds,$userId,$isUpdateCache = true){
        $str = implode(',',$fashionstaIds);
        $str = preg_replace('/(\d+)/','%s',$str);
        $sql = 'UPDATE cms_user_action SET Flag=%s WHERE Flag = 0  AND Type=4 AND UserID=%s and TypeID in ('.$str.')';

        $param = array(\haibao\jiepai\model\data\user\CmsUserAction::FLAG_DEL,$userId);
        $param = array_merge($param,$fashionstaIds);

        $this->query($sql,$param);

        if($isUpdateCache){
            $this->updateCacheFashioinStaMarkCount($fashionstaIds,-1);
        }
    }

    /**
     * 设置明星关注数缓存
     * @param $fashionStaIds
     */
    public function updateCacheFashioinStaMarkCount($fashionstaIds,$setCount = 1){
        if($fashionstaIds){
            $cache = new \haibao\jiepai\cache\FashionSta();
            foreach ($fashionstaIds as $id){
                $cache->setFashionstaMarkCount($id,$cache::FOLLOWEDNUM,$setCount);
            }
        }
    }

    public function getFashionistaTopList($limit = 100){
        $db = new \haibao\cms\data\Celebrity();
        $sql = 'SELECT c.Id,c.NameCn,c.NameEn,c.HotPoints,c.StarTypes,ci.ImageId,i.Filename,i.Height,i.Width,ci.ImageType FROM Celebrity c 
                LEFT JOIN CelebrityImage ci on ci.CelebrityId=c.Id
                LEFT JOIN ImageLibrary i on i.Id = ci.ImageId
                WHERE c.IsAppUse = 1 AND c.`Status` = 1 and (ci.ImageType = 2 or ci.ImageType = 4) ORDER BY c.HotPoints DESC LIMIT '.($limit + $limit);
        $result = $db->query($sql);
        $dataArr = array();
        while($result->fetch_assoc()){
            if(count($dataArr) >= $limit){
                return array_values($dataArr);
            }
            $data = array();
            if(empty($dataArr[$result->getData('Id')])){
                $data['FashionistaID'] = $result->getData('Id');
                $data['Name'] = $result->getData('NameCn');
                $data['NameFr'] = $result->getData('NameEn');
                $data['HotPoints'] = $result->getData('HotPoints');
                $data['Score'] = $result->getData('HotPoints');
                $data['Title'] = $result->getData('StarTypes');
                $data['FileID'] = $result->getData('ImageId');
                $data['Portrait'] = $result->getData('Filename');
                $data['FileHeight'] = $result->getData('Height');
                $data['FileWidth'] = $result->getData('Width');
                $data['CropX'] = 0;
                $data['CropY'] = 0;
                $dataArr[$result->getData('Id')] = $data;
            } else {
                if($result->getData('ImageType') == 4){
                    $data['FashionistaID'] = $result->getData('Id');
                    $data['Name'] = $result->getData('NameCn');
                    $data['NameFr'] = $result->getData('NameEn');
                    $data['HotPoints'] = $result->getData('HotPoints');
                    $data['Score'] = $result->getData('HotPoints');
                    $data['Title'] = $result->getData('StarTypes');
                    $data['FileID'] = $result->getData('ImageId');
                    $data['Portrait'] = $result->getData('Filename');
                    $data['FileHeight'] = $result->getData('Height');
                    $data['FileWidth'] = $result->getData('Width');
                    $data['CropX'] = 0;
                    $data['CropY'] = 0;
                    $dataArr[$result->getData('Id')] = $data;
                }
            }
        }
        return array_values($dataArr);
    }

    public function getFashionistaTopPicture($celebrityIds){
        $str = implode(',',$celebrityIds);
        $str = preg_replace('/(\d+)/','%s',$str);
        $dataList = array();
        $sql = 'select cat.CelebrityID,cac.ContentInfo from cms_article_celebrity cat LEFT JOIN cms_articles ca on cat.ArticleID = ca.ArticleID LEFT JOIN cms_article_content cac on cat.ArticleID = cac.ArticleID
                where cat.CelebrityID in ('.$str.') AND ca.Flag = 0 and ca.PublishStatus = 1 AND ca.ColumnID = 1 AND cac.Type = 0 GROUP BY cat.CelebrityID ORDER BY ca.PublishTime DESC';
        $result = $this->query($sql, $celebrityIds);
        while($result->fetch_assoc()){
            $dataList[$result->getData('CelebrityID')] = array('ContentInfo'=>$result->getData('ContentInfo'));
        }
        if($dataList){
            $dataList = \haibao\jiepai\data\BaseMysql::mergeDataAndImage($dataList,'ContentInfo');
        }
        return $dataList;
    }

    /**
     * 得明星关注数
     * @param $fashionstaId
     * @return array|null
     */
    public function getCacheFashionstaMarkCount($fashionstaId){
        $cache = new \haibao\jiepai\cache\FashionSta();
        $markCount = $cache->getFashionstaMarkCount($fashionstaId,$cache::FOLLOWEDNUM);
        if(!isset($markCount)){
            $markCount = 0;
            $sql = 'SELECT count(*) as MarkCount FROM cms_user_action WHERE TypeID=%s and Type=4';
            $result = $this->query($sql, array((int)$fashionstaId))->fetch_assoc();
            if(!empty($result) && isset($result['MarkCount'])){
                $markCount = $result['MarkCount'];
            }
            $cache->setFashionstaMarkCount($fashionstaId,$cache::FOLLOWEDNUM,$markCount);
        }

        return $markCount;
    }

    public function getNewsHot($fashionstaId){
        $cache = new \haibao\jiepai\cache\FashionSta();
        $list = $cache->getFashionstaNewsHot($fashionstaId);
        if(!isset($list)){
            $list = array();
            $sql = 'SELECT DISTINCT ca.ArticleID,ca.Title,ca.Scores,ca.Type,cac.ContentInfo as FileID FROM cms_articles ca
                    LEFT JOIN cms_article_content cac ON cac.ArticleID = ca.ArticleID
                    LEFT JOIN cms_article_celebrity cas ON cas.ArticleID = ca.ArticleID
                    WHERE cas.CelebrityID =%s AND ca.Type = 2 AND ca.Flag = 0 AND ca.PublishTime < NOW() AND ca.PublishStatus = 1 AND cac.Flag = 0 AND cac.Type = 0 ORDER BY ca.PublishTime DESC LIMIT 6';
            $result = $this->query($sql,array($fashionstaId));
            while($row = $result->fetch_assoc()){
                $row['Ratio'] = 1;
                $list[] = $row;
            }
            if($list){
                $list = \haibao\jiepai\data\BaseMysql::mergeDataAndImage($list,'FileID');
            }
            if($list){
                $cache->setFashionstaNewsHot($fashionstaId,$list);
            }
        }

        return $list;
    }

    public function getFashionstaAlsoLike($fashionstaId){
        $cache = new \haibao\jiepai\cache\FashionSta();
        return $cache->getFashionstaAlsoLike($fashionstaId);
    }

    public function getBoothInfo($fashionstaId){

        $staArr = array('Title'=>'星闻','SubTitle'=>'Latest News');
        $priArr = array('Title'=>'私照','SubTitle'=>'Photographs');

        $sql = 'SELECT t2.ContentInfo as ImageId FROM `cms_article_celebrity` t1 LEFT JOIN cms_article_content t2 ON t1.ArticleID = t2.ArticleID
                LEFT JOIN cms_articles t3 ON t1.ArticleID = t3.ArticleID WHERE t1.CelebrityID = %s AND t3.Type IN (1, 2) AND t2.Type = 0 AND t3.Flag = 0 ORDER BY t3.PublishTime DESC LIMIT 1';
        $result = $this->query($sql, array((int)$fashionstaId))->fetch_assoc();
        if(!empty($result) && isset($result['ImageId'])){
            $staArr = \haibao\jiepai\data\BaseMysql::mergeOneDataAndImage($staArr,$result['ImageId']);
        }
        $sql = 'SELECT t2.ContentInfo as ImageId FROM `cms_article_celebrity` t1 LEFT JOIN cms_article_content t2 ON t1.ArticleID = t2.ArticleID
                LEFT JOIN cms_articles t3 ON t1.ArticleID = t3.ArticleID WHERE t1.CelebrityID = %s AND t3.Type = 4 AND t2.Type = 4 AND t3.Flag = 0 ORDER BY t3.PublishTime DESC LIMIT 1';
        $result = $this->query($sql, array((int)$fashionstaId))->fetch_assoc();
        if(!empty($result) && isset($result['ImageId'])){
            $priArr = \haibao\jiepai\data\BaseMysql::mergeOneDataAndImage($priArr,$result['ImageId']);
        }

        return array($staArr,$priArr);
    }

    public function getPrivatePhotos($fashionstaId,$userId,$limit = 31,$lastObjectId = 0,$versionCompare=0){
        $contentIds = array();
        $articleIds = array();
        $pictureIds = array();
        $list = array();
        $sql = 'SELECT t1.ArticleID,t3.ID AS ContentID,t3.ContentInfo AS FileID,t2.CelebrityID AS SourceTypeID  FROM cms_articles t1
                INNER JOIN cms_article_celebrity t2 ON t1.ArticleID = t2.ArticleID
                INNER JOIN cms_article_content t3 ON t1.ArticleID = t3.ArticleID 
                WHERE t2.CelebrityID = %s AND t1.Type = 4 AND t1.Flag = 0';

        if($lastObjectId){
            $sql .= ' AND t1.ArticleID < '.$lastObjectId;
        }
        $sql .= ' ORDER BY t1.ArticleID DESC ';

        $sql .=  ' LIMIT '.$limit;

        $result = $this->query($sql,array($fashionstaId));
        while($row = $result->fetch_assoc()){
            $row['IsPictureCollect'] = 0;
            if($versionCompare){
            	$row['IsPicturePraise'] = 0;
            	$row['Watermark'] = "@watermark";
            	$row['CommentCount'] = 0;
            	$row['CollectSource'] = '';
            }else {
            	$row['IsPicturePraise'] = 0;
            }
            $row['SourceType'] = 4;
            $list[] = $row;
            $contentIds[] = $row['ContentID'];
            $articleIds[] = $row['ArticleID'];
            $pictureIds[] = $row['FileID'];
        }
        if($userId){
            if($contentIds){
                $str = implode(',',$contentIds);
                $str = preg_replace('/(\d+)/','%s',$str);
                $sql = 'SELECT ContentID from cms_album_pictures where Flag = 0 AND UserID=%s AND ContentID in ('.$str.')';
                $param = array($userId);
                $param = array_merge($param,$contentIds);
                $result =  $this->query($sql,$param);
                while($row = $result->fetch_assoc()){
                    foreach ($list as $k=>$v){
                        if($v['ContentID'] == $row['ContentID']){
                            $v['IsPictureCollect'] = 1;
                            $list[$k] = $v;
                            break;
                        }
                    }
                }
            }
          
            if($versionCompare){
            	if($pictureIds){
            		$data = new \haibao\jiepai\data\User();
            		$praisePictureIds = $data->getUserActions(\haibao\jiepai\model\data\user\CmsUserAction::TYPE_PICTURE_PRAISE,$pictureIds,$userId);
       		
            		if($praisePictureIds){
            			foreach ($list as $k=>$v){
            				if(isset($praisePictureIds[$v['FileID']]) && !empty($praisePictureIds[$v['FileID']])){
            					$v['IsPicturePraise'] = 1;
            					$list[$k] = $v;
            				}
            			}
            		}
            	}
            	
            }
            
            if(!$versionCompare && $articleIds){
                $data = new \haibao\jiepai\data\User();
                $praiseIds = $data->getUserActions(\haibao\jiepai\model\data\user\CmsUserAction::TYPE_ARTICLE_PRAISE,$articleIds,$userId);
                if($praiseIds){
                    foreach ($list as $k=>$v){
                        if(!empty($praiseIds[$v['ArticleID']])){
                            $v['IsPicturePraise'] = 1;
                            $list[$k] = $v;
                        }
                    }
                }
            }
        }
        if($versionCompare){
        	if($pictureIds){
        		$commentResult = \haibao\jiepai\business\Comment::getCommentCountByImageIds($pictureIds);
        		$sourceResult = \haibao\jiepai\business\Picture::getCollectSource($pictureIds);

        		if($commentResult){
        			foreach ($list as $k=>$v){
        				if(isset($commentResult[$v['FileID']]) && !empty($commentResult[$v['FileID']])){
        					$v['CommentCount'] = (int)$commentResult[$v['FileID']];
        					$list[$k] = $v;
        				}
        			}
        		}
        		if($sourceResult){
        			foreach ($list as $k=>$v){
        				if(isset($sourceResult[$v['FileID']]) && !empty($sourceResult[$v['FileID']])){
        					$v['CollectSource'] = $sourceResult[$v['FileID']];
        					$list[$k] = $v;
        				}
        			}
        		}		
        	}
        }

        if($list){
            $list = \haibao\jiepai\data\BaseMysql::mergeDataAndImage($list,'FileID');
        }

        return $list;
    }

    public function getPrivatePhotosCount($fashionstaId){
        $sql = 'SELECT count(t1.ArticleID) as count FROM cms_articles t1
                INNER JOIN cms_article_celebrity t2 ON t1.ArticleID = t2.ArticleID
                INNER JOIN cms_article_content t3 ON t1.ArticleID = t3.ArticleID 
                WHERE t2.CelebrityID = %s AND t1.Type = 4 AND t1.Flag = 0';
        $result = $this->query($sql, array((int)$fashionstaId))->fetch_assoc();
        if(!empty($result)){
            return $result['count'];
        }
        return 0;
    }

    public function getOtherArticles($fashionstaId,$limit = 1){
        $list = array();
        $sql = 'SELECT ca.ArticleID,ca.Title,ca.Type,cac.ContentInfo as FileID FROM cms_articles ca
                LEFT JOIN cms_article_celebrity cat ON ca.ArticleID = cat.ArticleID
                LEFT JOIN cms_article_content cac ON ca.ArticleID = cac.ArticleID
                WHERE cac.Type = 0 AND ca.PublishStatus = 1 AND ca.Flag = 0 AND ca.Type = 1 AND cat.CelebrityID = %s ORDER BY ca.Scores desc LIMIT '.$limit;

        $result = $this->query($sql,array($fashionstaId));
        while($row = $result->fetch_assoc()){
            $list[] = $row;
        }

        if($list){
            $list = \haibao\jiepai\data\BaseMysql::mergeDataAndImage($list,'FileID');
        }

        return $list;
    }

    public function getFashionistaArticles($fashionstaId,$lastTime = 0,$limit = 30){
        $sql = 'SELECT DISTINCT t2.ContentLink as Url,t2.ArticleID,t2.Type,t2.Title,t2.PublishTime FROM `cms_article_celebrity` t1  
                inner JOIN cms_articles t2 on t1.ArticleID = t2.ArticleID AND t2.Type in (1,2,5,101,102,103,104,105,106) 
                WHERE t2.Flag = 0 AND t2.PublishStatus=1 AND t2.PublishTime < NOW() AND t1.CelebrityID = %s';
        if($lastTime){
            $sql .= ' AND t2.PublishTime < "'.date('Y-m-d H:i:s',$lastTime).'"';
        }
        $sql .= ' ORDER BY t2.PublishTime desc LIMIT '.$limit;
        $result = $this->query($sql,array($fashionstaId));
        $list = array();
        while($row = $result->fetch_assoc()){
            $list[] = $row;
        }
        return $list;
    }

    public function getHaibaoArticleList($fashionstaId,$lastTime = 0,$limit = 30){
        $sql = ' SELECT ca.ArticleID,ca.Title,ca.PublishTime,ca.ContentLink as Url,cac.ContentInfo as FileID from cms_article_celebrity cat
                INNER JOIN cms_articles ca on cat.ArticleID = ca.ArticleID AND ca.Type = 5 AND ca.Flag = 0 AND ca.PublishStatus = 1
                INNER JOIN cms_article_content cac on ca.ArticleID = cac.ArticleID AND cac.Flag = 0 AND cac.Type = 0
                WHERE cat.CelebrityID=%s';
        if($lastTime){
            $sql .= " AND ca.PublishTime < '".date('Y-m-d H:i:s',$lastTime)."' ";
        }
        $sql .= ' ORDER BY ca.PublishTime desc limit '.$limit;
        $result = $this->query($sql,array($fashionstaId));
        $list = array();
        while($row = $result->fetch_assoc()){
            $list[] = $row;
        }

        if($list){
            $list = \haibao\jiepai\data\BaseMysql::mergeDataAndImage($list,'FileID');
        }

        return $list;
    }
    //获取达人积分最高的四篇文章
    public function getTopFourJiePaiArticles($TagId){
        $sql = "SELECT ca.ArticleID,cac.ContentInfo
             from cms_articles ca 
             LEFT JOIN cms_article_celebrity cat on ca.ArticleID = cat.ArticleID 
             LEFT JOIN cms_article_content cac on ca.ArticleID=cac.ArticleID 
             WHERE cat.CelebrityID=%s AND ca.Type=2 AND cac.Type=0 AND cac.Flag=0 AND ca.PublishStatus = 1 AND ca.Flag = 0 
             ORDER BY ca.Scores desc limit 4";
        $result = $this->query($sql,array($TagId));
        $dataList = array();
        while ($row = $result->fetch_assoc()){
            array_push($dataList, $row);
        }
        if($dataList){
            $dataList = $this->mergeDataAndImage($dataList,'ContentInfo');
        }
        return $dataList;
    }

    public function getHotRecommendFashionistas($userId,$limit = null){
        $cache = new \haibao\jiepai\cache\FashionSta();

        $cacheData = $cache->getHotRecommendFashionistas();
        if(!empty($cacheData)){
            foreach ($cacheData as $k=>$v){
                $sql = 'SELECT count(*) as count from cms_user_action WHERE Flag = 0 AND Type=4 AND TypeID='.$v['FashionistaID'].'  AND UserID='.$userId;
                $result = $this->query($sql)->fetch_assoc();
                $v['IsFollow'] = 0;
                if(!empty($result)){
                    $v['IsFollow'] = 1;
                }
                $cacheData[$k] = $v;
                if($k == $limit){
                    break;
                }
            }
        }

        return $cacheData;
    }
    
    public function InsertIntoSearchHistory($keyword,$userId){
    	$sql = "INSERT INTO cms_user_search_history(KeyWord,UserID,CreateTime,Flag) values (%s,%s,%s,%s) ";
		$this->query($sql,array($keyword,$userId,new \DateTime(),0));
    }

    public function isFashionista($celebrityId){
        $sql = 'SELECT count(*) as count FROM cms_data_map WHERE DataType =2 AND CmsDataID = %s';
        $result = $this->query($sql, array((int)$celebrityId))->fetch_assoc();
        if(!empty($result)){
            return $result['count'];
        }
        return 0;

    }
}